import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import Redis from 'ioredis';
import { InjectRepository } from '@nestjs/typeorm';
import { Clerk } from 'src/core/entities/clerk.entity';
import { User } from 'src/core/entities/user.entity';
import { Repository } from 'typeorm';
import { ChatRolesTypes, ChatRoleToken } from './chat.dto';
import { WsException } from '@nestjs/websockets';
import { InjectRedis } from '@nestjs-modules/ioredis';

@Injectable()
export class ChatService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(Clerk)
    private readonly clerkRepository: Repository<Clerk>,
    private readonly jwtService: JwtService,
    @InjectRedis()
    private readonly redis: Redis,
  ) {}

  /**
   * 解析并验证认证信息
   * @param token 身份认证信息
   * @returns 解析结果
   */
  async validateToken(token: string): Promise<ChatRoleToken> {
    try {
      const payload = this.jwtService.verify<ChatRoleToken>(token);
      const { type, id } = payload;
      if (type == ChatRolesTypes.USER) {
        const exist = await this.userRepository.existsBy({ id });
        if (exist) {
          return payload;
        }
        throw new WsException('Invalid role id');
      }
      if (type == ChatRolesTypes.CLERK) {
        const exist = await this.clerkRepository.existsBy({ id });
        if (exist) {
          return payload;
        }
        throw new WsException('Invalid role id');
      }
      throw new WsException('Invalid role');
    } catch (error) {
      console.error(error);
      throw new WsException('Invalid Authorization Token');
    }
  }
}
